#!/usr/bin/env bash


distributionUrl="https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-8/v8.5.42/bin/apache-tomcat-8.5.42.tar.gz"

tomcat_dir="$HOME/.tomcat"
tomcat_wrapper="$tomcat_dir/wrapper"
tomcat_dist="$tomcat_dir/dists"
tomcat_file="$tomcat_dist/${distributionUrl##*/}"
tomcat_bin="$tomcat_home/bin"
# 如果未配置或配置错误会自动生成
tomcat_home=""

err_quit(){ if [ $1 -ne 0 ]; then echo $2; exit $1; fi;}

install_(){
  [ -d "$tomcat_dist" ] || mkdir -p "$tomcat_dist"
  curl -SL# "$distributionUrl" -o "$tomcat_file"
  err_quit $? "下载文件失败"
  tar -zxf "$tomcat_file" -C "$tomcat_wrapper"
  tomcat_home="$tomcat_wrapper/$(echo "${distributionUrl##*/}"|sed 's/\.tar\.gz$//')"
}

# 检查有没有tomcat
check_bin(){
  [ -d "$tomcat_home" ] && [ -f "$tomcat_home/bin/catalina.sh" ] && return
  [ -d "$tomcat_wrapper" ] || mkdir -p "$tomcat_wrapper"
  dirs=($(ls "$tomcat_wrapper" -aF -1 -I . -I .. |grep '/$'|sort -r))
  for dir in "${dirs[@]}"; do
    if [[ -n "$dir" && -f "$tomcat_wrapper/$dir/bin/catalina.sh" ]]; then
      tomcat_home="$tomcat_wrapper/$(echo "$dir"|sed 's#/$##')"
      return 0
    fi
  done
  return 1
}

# 检查 CALINA_BASE 是否有配置文件
check_dir(){
  [ -z "$CATALINA_BASE" ] && return
  [ -d "$CATALINA_BASE" ] || mkdir -p "$CATALINA_BASE"
  if [ ! -d "$CATALINA_BASE/conf" ]; then
    cp -r "$tomcat_home/conf" "$CATALINA_BASE/conf"
  fi
  [ -d "$CATALINA_BASE/logs" ] || mkdir "$CATALINA_BASE/logs"
  [ -d "$CATALINA_BASE/temp" ] || mkdir "$CATALINA_BASE/temp"
}

help(){
  echo "
用法: $0 [options] <commands ...>

参数:

  -h , --help , -?              输出帮助信息
  --catalina-base               指定 tomcat 配置文件目录
  --check-dir                   检查 CATALINA_BASE 配置文件目录

命令:

  <没有参数|run>                前台运行
  start                         开启服务
  stop                          结束服务
  restart                       重启服务
  check|status                  查看状态
  install                       安装
  install-service               安装为服务
  on                            开机启动
  off                           开机不启动
  service <params>              即运行 service $SERVICE_NAME <params>
  log                           查看日志
"
}

check_bin

# 获取最新版本
# curl -sSL https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-8/|grep -o 'href="v8[^"]\+"'|grep -o '[0-9\.]\+'|sort|tail -1

# 前台运行
run(){
  bash "$tomcat_bin/catalina.sh" run
  exit $?
}

for pm in "$@"; do
  case "$pm" in
    --catalina-base=*)
      export CATALINA_BASE="${pm#*=}"
      shift;;
    --check-dir)
      check_dir
      shift;;
    run)
      run;;
    info)
      bash "$tomcat_bin/catalina.sh" version
      exit $?;;
    --help|-h|-\?)
      help
      exit 0;;
  esac
done

[[ $# -eq 0 ]] && run
tomcatw="$tomcat_home/bin/$1"
shift
bash "$tomcatw" "$@"

